<template>
    <div class="app-container background" style="padding: 0;">
        <div class="top-title-border top-title-background">
            <i class="el-icon-back"
                style="color: #ffffff;width:5%;height: 40px;display: inline-block;font-size: 20px;line-height: 40px;padding-left: 20px;cursor: pointer;z-index: 2;position: relative;"
                @click="goBack"></i>
            <span
                style="position: absolute;top:0;left: 0;right: 0;z-index: 1;text-align: center;color: #ffffff;font-size: 18px;font-weight: bold;line-height: 40px;">{{
                    device.name }}数据分析</span>
            <div style="font-size: 14px;font-weight: bold;color: #ffffff;display: inline">
                <div class="info-box">
                    <svg-icon style="fill: yellow;" icon-class="alarm"></svg-icon>
                    <span>二级报警：{{ alarmCount.get("二级报警") }}</span>
                </div>
                <div class="info-box">
                    <svg-icon style="fill: red;" icon-class="alarm" />
                    <span>一级报警：{{ alarmCount.get("一级报警") }}</span>
                </div>
                <div class="info-box">
                    <span>通讯状态：</span> <span v-if="device.onLine" style="color: green;font-size: 13px;">在线</span>
                    <span v-else style="color: grey;font-size: 13px;">离线</span>
                </div>
            </div>
        </div>

        <CompareDialog :dialogVisible="showCompare" :device="device" @visibleChange="cancel"></CompareDialog>

        <el-dialog title="自定义时间" :visible.sync="showDatePicker" width="40%">
            <span style="color: #ffffff;">请选择时间段：</span>
            <el-date-picker v-model="timeRange" type="datetimerange" start-placeholder="开始日期" end-placeholder="结束日期"
                align="center" :default-time="['08:00:00']"></el-date-picker><!-- :picker-options="pickerOptions" -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="showDatePicker = false">取 消</el-button>
                <el-button type="primary" @click="confirmDate">确 定</el-button>
            </span>
        </el-dialog>

        <el-card style="width: 100%;height: 47%;" class="data-card">
            <div slot="header" style="display: flex;justify-content: space-between;">
                <span>数据信息</span>
                <div style="position: relative;z-index: 100;">
                    <span v-hasPermi="['oil:data:compare']"
                        style="font-size: 16px;color: #06A3E6;cursor: pointer;margin-right: 10px;"
                        @click="showCompare = true">跨设备数据对比</span>
                    <el-radio-group size="mini" v-model="range"
                        style="margin-top: -10px;border-top-right-radius: 0;border-bottom-right-radius: 0;"
                        @input="timeChange">
                        <el-radio-button label="0">实时</el-radio-button>
                        <el-radio-button label="1">24H</el-radio-button>
                        <el-radio-button label="2">72H</el-radio-button>
                        <el-radio-button label="3" @click.native="showDatePicker = true">自定义</el-radio-button>
                        <el-button v-hasPermi="['oil:data:download']" @click="showDataDownload = true" size="mini"
                            style="position: relative;top:7px;border-top-left-radius: 0;border-bottom-left-radius: 0;padding: 0 15px;height: 27px;">
                            <svg-icon icon-class="download-arrow"
                                style="fill: #1D3870;width: 16px;height: 18px;"></svg-icon>
                        </el-button>
                    </el-radio-group>
                </div>
            </div>
            <div ref="chart" id="chart" v-loading="chartLoading" element-loading-text="加载中"
                element-loading-spinner="el-icon-loading"
                style="width: 100%;height: 95%;margin-top: -2%;position: relative;z-index: 0;">
            </div>
            <el-checkbox-group v-model="checkedList" @change="getVariableData" :max="5"
                style="height: 5%;display: flex;justify-content: center;flex-wrap: wrap;">
                <el-checkbox v-for="key in variableKeys" :key="key" :label="key">{{ variables.get(key).name
                    }}</el-checkbox>
            </el-checkbox-group>
        </el-card>

        <el-dialog title="下载数据" :visible.sync="showDataDownload" width="40%">
            <el-form v-model="downloadQuery" label-width="100px">
                <el-form-item label="请选择时间段" prop="timeRange">
                    <el-date-picker v-model="downloadQuery.timeRange" type="datetimerange" start-placeholder="开始日期"
                        end-placeholder="结束日期" align="center" :default-time="['00:00:00']"></el-date-picker>
                    <!--开启选择时间限制 :picker-options="pickerOptions" -->
                </el-form-item>
                <el-form-item label="请选择指标">
                    <el-tooltip effect="dark" content="不选择该项时将下载所有指标数据" placement="bottom">
                        <el-select v-model="downloadQuery.fields" placeholder="指标名称" style="width: 400px;" clearable
                            :multiple="true">
                            <el-option v-for="variable in variableList" :key="variable.key" :label="variable.name"
                                :value="variable.key" />
                        </el-select>
                    </el-tooltip>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="showDataDownload = false">取 消</el-button>
                <el-button type="primary" @click="confirmDownLoad">确 定</el-button>
            </span>
        </el-dialog>

        <el-card style="width: 100%;height: 47%;margin-top: 5px;" class="variable-card">
            <div slot="header">
                <div @click="current = 0" :class="{ tab_header: current == 0, tab_header_inactive: current == 1 }">实时数据
                </div>
                <div @click="current = 1;getLastImageData()" :class="{ tab_header: current == 1, tab_header_inactive: current == 0 }">图片数据
                </div>
            </div>
            <div v-if="current == 0">
                <el-table class="scroll-table" v-loading="loading" :data="detailVariableData" :max-height="350"
                    ref="scroll_Table" @mouseenter.native="autoScroll(true)" @mouseleave.native="autoScroll(false)">
                    <el-table-column label="序号" prop="id" width="80" align="center">
                        <template slot-scope="scope">
                            {{ scope.$index + 1 }}
                        </template>
                    </el-table-column>
                    <el-table-column label="参数名称" align="center">
                        <template slot-scope="scope">
                            {{ variables != null ? variables.get(scope.row.variableKey).name : "" }}
                        </template>
                    </el-table-column>
                    <el-table-column label="实时数值" prop="current" align="center"></el-table-column>
                    <el-table-column label="参数单位" align="center">
                        <template slot-scope="scope">
                            {{ variables != null ? variables.get(scope.row.variableKey).unit : "" }}
                        </template>
                    </el-table-column>
                    <el-table-column label="最大值" prop="max" align="center"></el-table-column>
                    <el-table-column label="最大值时间" prop="maxTime" align="center" width="95"></el-table-column>
                    <el-table-column label="最小值" prop="min" align="center"></el-table-column>
                    <el-table-column label="最小值时间" prop="minTime" align="center" width="95"></el-table-column>
                    <el-table-column label="平均值" prop="average" align="center"></el-table-column>
                    <el-table-column label="数值说明" width="400" align="center">
                        <template slot-scope="scope">
                            {{ variables != null ? variables.get(scope.row.variableKey).remark : "" }}
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div v-else-if="current == 1" style="display: flex;justify-content: space-around;height: 450px;">
                <img :src="prefix+imageData.imagePath" style="height: 85%;"></img>
                <div style="display: inline-block;width: 60%;height: 90%;overflow-y: auto;padding-left: 10px;line-height: 35px;display: flex;flex-direction: column;flex-wrap: wrap;align-content: space-around;">
                    <span v-for="(value,key) in imageData" v-if="key != 'imagePath' && key != '_id' && key != 'ts' && key != 'deviceCode'" style="display: flex;justify-content: space-between;">
                        <span><dict-tag :options="dict.type.oil_image_attribute" :value="key" style="display: inline;"/>: </span><span style="display: inline-block;width: 50px;"></span>{{ value }}<br>
                    </span>
                </div>
            </div>
        </el-card>
    </div>
</template>
<script>
import * as echarts from 'echarts'
import { getDevice, getDeviceByCode } from "@/api/oil/device";
import { listVariable } from "@/api/oil/variable";
import { listVariableData, getDetailVariable, getDeviceDataLast, exportDeviceData, getDeviceImageDataLast } from '../../../api/oil/device_data';
import { svrapi } from '../../../utils/request';
import { recordCountByCode } from '../../../api/oil/record';
import DateTool from '../../../utils/DateTool';
import CompareDialog from './compareDialog.vue';
export default {
    name: 'Analysis',
    components: { CompareDialog },
    dicts: ['oil_image_attribute'],
    data() {
        return {
            device: {},
            dataChart: null,
            range: 0,
            variableKeys: [], //设备可选指标
            variableList: [],  //所有指标列表
            variables: null,  //所有指标 Map<variableKey,variable>
            checkedList: [], //选中指标
            xData: [],
            yData: [],
            legend: [],
            resizeObserver: null,
            current: 0, //用于底部实时数据与实验室数据切换
            detailVariableData: [],
            scrolltimer: '',
            loading: false, //底部表格加载
            chartLoading: false, //图表加载
            //时间选择
            startTime: null,
            endTime: null,
            showDatePicker: false,
            timeRange: null,
            pickerOptions: null,
            startDate: null,
            showCompare: false, //设备数据对比对话框
            showDataDownload: false,
            downloadQuery: {},
            alarmCount: new Map(),
            timer: null, //定时器
            imageData:null, //图片数据
            imageloading: true, //图片加载状态
            prefix: null, //图片前缀
        }
    },
    created() {
        this.prefix = svrapi;
        this.timeChange();
        this.initPickerOption();
        const deviceCode = this.$route.params && this.$route.params.deviceCode;
        console.log("设备编码： "+deviceCode);
        if (deviceCode) {
            getDeviceByCode(deviceCode).then((response) => {
                this.device = response.data;
                this.getVariables();
                this.getDetailVaribaleData();
            })
            this.getAlarmCount(deviceCode);
        }
        window.addEventListener('resize', this.handleResize);
    },
    mounted() {
        this.dataChart = echarts.init(document.getElementById("chart"));
        this.echartInit();
        this.resizeObserver = new ResizeObserver(entries => {
            this.handleResize();
        })
        this.resizeObserver.observe(this.$refs.chart);
        this.autoScroll();
    },
    beforeDestroy() {
        this.resizeObserver.unobserve(this.$refs.chart);
        this.resizeObserver.disconnect();
        window.removeEventListener('resize', this.handleResize);
        if (this.dataChart) {
            this.dataChart.dispose();//清理图表实例
        }
        this.autoScroll(true);
    },
    methods: {
        getLastImageData() {
            if (!this.device.code) return;
            this.imageloading = true;
            getDeviceImageDataLast(this.device.code).then(res => {
                this.imageloading = false;
                this.imageData = res.data;
            })
        },
        //查询报警统计
        getAlarmCount(deviceCode) {
            //查询未处理状态报警记录
            recordCountByCode({ "deviceCode": deviceCode, "state": 0 }).then(res => {
                this.alarmCount = new Map(res.data.map(item => [item["alarmLevelName"], item["count"]]));
                console.log(this.alarmCount)
            })
        },
        //控制自定义查询时间时最长查询三个月
        initPickerOption() {
            this.pickerOptions = {
                // onPick：选中日期时的回调函数，在这里对选中的日期进行处理{maxDate：后选中日期；minDate：第一个选中的日期}
                onPick: ({ maxDate, minDate }) => {
                    this.startDate = minDate && minDate.getTime()
                    if (maxDate) {
                        // 选中后一个时，要把第一个的赋值清空
                        this.startDate = ''
                    }
                },
                disabledDate: (time) => {
                    // 选中第一个后，后一个前后3个月可选，超出的不可选，超出当前天也不可选，这里的月份按需求设定
                    const minTime = new Date(this.startDate).setMonth(new Date(this.startDate).getMonth() - 3)
                    const maxTime = new Date(this.startDate).setMonth(new Date(this.startDate).getMonth() + 3)
                    return time.getTime() > Date.now() || (this.startDate ? (time.getTime() < minTime || time.getTime() > maxTime) : false)
                }
            }
        },
        handleResize() {
            if (this.dataChart) {
                this.dataChart.resize();
            }
        },
        goBack() {
            //保存上一页状态并返回
            this.$router.back();
            console.log('back');
        },
        echartInit() {
            this.dataChart.clear();
            var option = {
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: this.legend,
                    left: 70,
                    top: 20,
                    textStyle: {
                        color: "#fff"
                    }
                },
                dataZoom: [{ // 开启鼠标缩放
                    type: 'inside', // 内置型数据区域缩放组件
                    start: 0, // 数据窗口范围的起始百分比
                    end: 100 // 数据窗口范围的结束百分比
                }, {
                    xAxisIndex: [0]
                }],
                grid: {
                    left: '1%',
                    right: '1%',
                    bottom: '3%',
                    containLabel: true
                },
                toolbox: {
                    // feature: {
                    //     saveAsImage: {}
                    // }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    axisLabel: {
                        formatter: function (value) {
                            var time = value.split(" ");
                            var date = time[0].substring(5);
                            return time[1] + "\n" + date
                        },
                        show: true,
                        textStyle: {
                            color: "#fff"
                        }
                    },
                    // splitLine: { // 设置X轴分割线
                    //     show: true
                    // },
                    data: this.xData
                },
                yAxis: {
                    type: 'value',
                    splitLine:{
                        lineStyle:{// 设置y轴分割线
                            color:['#eee'],
                            type:'dashed'
                        }
                    },
                    axisLabel: {
                        textStyle: {
                            color: "#fff"
                        }
                    }
                },
                darkMode: true,
                series: this.yData
            }
            //当数据为空时显示y轴分割线
            if (this.yData == null || this.yData.length <= 0) {
                option.yAxis.min = 0;
                option.yAxis.max = 80;
                option.yAxis.interval = 10;
            }
            option && this.dataChart.setOption(option);
        },
        //获取每个指标详情，当前值，最大值，最小值等
        getDetailVaribaleData() {
            if (!this.device.code) return;
            this.loading = true;
            var queryData = { deviceCode: this.device.code, startTime: this.startTime, endTime: this.endTime }
            getDetailVariable(queryData).then(res => {
                this.loading = false;
                this.detailVariableData = res.data;
            })
        },
        getVariables() {
            listVariable({ pageSize: 5000, pageNum: 1 }).then(response => {
                if (response.rows != null) {
                    this.variableList = response.rows;
                    this.variables = new Map(response.rows.map(obj => [obj["key"], obj]))
                }
                if (this.device.variableKeys != null) {
                    this.variableKeys = [...new Set(this.device.variableKeys.split(","))]
                    this.variableKeys.sort((a, b) => {
                        return this.variables.get(a).order - this.variables.get(b).order;
                    })//按照顺序排列
                    //只取指定的前12个指标显示
                    this.variableKeys = this.variableKeys.slice(0, 12);
                    this.checkedList = this.variableKeys.slice(0, 5);
                    this.getVariableData();
                }
            })

        },
        getVariableData() {
            var queryData = { "deviceCode": this.device.code, "fields": this.checkedList, startTime: this.startTime, endTime: this.endTime };
            this.chartLoading = true;
            listVariableData(queryData).then(response => {
                var deviceData = response.data;
                this.xData = deviceData.map(item => item.timeStamp);
                this.legend = this.checkedList.map(key => this.variables.get(key)?.["name"]);
                this.yData = [];
                for (let i = 0; i < this.checkedList.length; i++) {
                    var obj = { name: this.variables.get(this.checkedList[i]).name, type: 'line', large: true, largeThreshold: 1000, showSymbol: false }; //large:true 开启大数据量优化 largeThreshold:大数据量阈值，超过该值开启优化 
                    obj.data = deviceData.map(item => item[this.checkedList[i]]);
                    this.yData.push(obj);
                }
                console.log(this.yData);
                this.chartLoading = false;
                this.echartInit();
            })
        },
        //表格内容自动滚动
        autoScroll(stop) {
            const table = this.$refs.scroll_Table
            // 拿到表格中承载数据的div元素
            const divData = table.$refs.bodyWrapper
            // 拿到元素后，对元素进行定时增加距离顶部距离，实现滚动效果(此配置为每100毫秒移动1像素)
            if (stop) {
                //再通过事件监听，监听到 组件销毁 后，再执行关闭计时器。
                window.clearInterval(this.scrolltimer)
            } else {
                this.scrolltimer = window.setInterval(() => {
                    // 元素自增距离顶部1像素
                    divData.scrollTop += 1
                    // 判断元素是否滚动到底部(可视高度+距离顶部=整个高度)
                    if (divData.clientHeight + divData.scrollTop == divData.scrollHeight) {
                        // 重置table距离顶部距离
                        divData.scrollTop = 0
                        // 重置table距离顶部距离。值=(滚动到底部时，距离顶部的大小) - 整个高度/2
                        // divData.scrollTop = divData.scrollTop - divData.scrollHeight / 2
                    }
                }, 150) // 滚动速度
            }
        },
        timeChange() {
            var value = this.range;
            clearInterval(this.timer);
            if (value == 3) {
                this.showDatePicker = true;
            } else {
                // this.clearChart();
                // this.getDetailVaribaleData();
                // this.checkedList = this.variableKeys.slice(0, 5);//默认选中前5个指标
                // this.getVariableData();
                this.updateData();
                this.timer = setInterval(() => {
                    this.updateData();
                }, 1000 * 60 * 5); //每5分钟更新一次数据
            }
        },
        updateData() {
            var value = this.range;
            if (value == 0) {
                this.endTime = DateTool.now();
                this.startTime = DateTool.dateToStr(DateTool.addHour(null, -1));
            } else if (value == 1) {
                this.endTime = DateTool.now();
                this.startTime = DateTool.dateToStr(DateTool.addHour(null, -24));
            } else if (value == 2) {
                this.endTime = DateTool.now();
                this.startTime = DateTool.dateToStr(DateTool.addHour(null, -72));
            }
            this.getDetailVaribaleData();
            this.clearChart();
            this.checkedList = this.variableKeys.slice(0, 5);//默认选中前5个指标
            this.getVariableData();
        },
        confirmDate() {
            console.log(this.timeRange);
            this.startTime = DateTool.dateToStr(this.timeRange[0]);
            this.endTime = DateTool.dateToStr(this.timeRange[1]);
            this.showDatePicker = false;
            this.getDetailVaribaleData();
            this.clearChart();
            this.checkedList = this.variableKeys.slice(0, 5);
            this.getVariableData();
        },
        //清空表格内容
        clearChart() {
            if (this.dataChart) {
                this.xData = [];
                this.yData = [];
                this.echartInit();
            }
        },
        cancel(value) {
            this.showCompare = value;
        },
        confirmDownLoad() {
            if (!this.downloadQuery.timeRange) return this.$modal.msgWarning("请选择下载时间段!");
            if (!this.device) return this.$modal.msgWarning("当前页设备失效，请重新进入!");
            this.downloadQuery.startTime = DateTool.dateToStr(this.downloadQuery.timeRange[0]);
            this.downloadQuery.endTime = DateTool.dateToStr(this.downloadQuery.timeRange[1]);
            this.downloadQuery.deviceCode = this.device.code;
            this.downloadData('oil/data/device/export',
                this.downloadQuery
                , `${this.device.name}_${DateTool.now()}.xlsx`)
            this.showDataDownload = false;
            this.downloadQuery = {}
        }
    }
}
</script>
<style>
.tab_header_inactive {
    display: inline-block;
    padding: 10px 15px;
    cursor: pointer;
}

.tab_header {
    display: inline-block;
    padding: 10px 15px;
    background-color: #01152D;
    cursor: pointer;
}

.info-box {
    float: right;
    margin: 10px;
}

.data-card .el-card__header {
    height: 10%;
    padding-bottom: 0;

}

.data-card .el-card__body {
    height: 90%;
    padding: 0 20px;
}

.variable-card .el-card__header,
.variable-card .el-card__body {
    padding: 0;
}

.scroll-table .el-table__row {
    background-color: transparent !important;
}
</style>